<?php

namespace app\common\model;
use houdunwang\Cart;
use think\Model;

class Order extends Model
{
    /**
     * 生成订单
     * 1.提交成功
     * 2.收货人
     * 3.收货地址
     * 4.电话
     * @param $post
     */
    public function add($post)
    {
        #查询用户id
        $userid = session('id');
        #根据用户id查询地址表
        $addressdata = (new Address())->where('user_id',$userid)->find();
        #拿到地址表id
        $address_id = $addressdata['id'];
        #查询所有购物车里商品数据
        $data= session('cart');
//        halt($data);
        #订单表(order)
        $OrderModel = new Order();
        #订单号
        $OrderModel->order_num  = '18'.time();
        #订单状态
        $OrderModel->status     = 1;
        #订单的备注
        $OrderModel->memo       = $post['memo'];
        #订单的总价
        $OrderModel->total_price= $post['price'];
        #订单关联用户表
        $OrderModel->user_id    = $userid;
        #购买用户名字
        $OrderModel->username    = $addressdata['names'];
        #订单关联地址表
        $OrderModel->address_id    = $address_id;
        $OrderModel->save();


        foreach($data['goods'] as $k =>$v)
        {
            #订单商品表(ordergoods )
            $OrderGoods = new  Ordergoods();
            #商品名称
            $OrderGoods ->title =  $v['name'];
            #价格
            $OrderGoods->price= $post['price'];
            #预览图
            $OrderGoods->pic = $v['options']['img'];
            #关联订单表oid
            $OrderGoods->oid = $OrderModel->id;
            #大小
            $OrderGoods->size =$v['options']['size'];
            #颜色
            $OrderGoods->color = $v['options']['color'];
            #数量
            $OrderGoods->num = $v['num'];
            $OrderGoods->save();

        }

        #订单存入session
        session('order_num',$OrderModel->order_num );
        session('cart', null);
        return 1;
    }
    /**
     * 订单表关联订单商品表(一对多)
     * @return \think\model\Relation
     */
    public function ordergoods()
    {
        return $this->hasMany('ordergoods','oid');
    }

}
